/*
 * jETeL/CloverETL - Java based ETL application framework.
 * Copyright (c) Javlin, a.s. (info@cloveretl.com)
 *  
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
package org.jetel.graph.runtime.tracker;

import org.jetel.data.DataRecord;
import org.jetel.data.Token;
import org.jetel.graph.Node;

/**
 * Token tracker for components which create N out-tokens for one read token, where 1st 
 * of the N out-tokens is considered to be the single read token.
 * 
 * IDs of out-tokens are watched and if currently written token has equal ID as the last token,
 * then these out-tokens are linked. Otherwise no action is made; first written token from group
 * of out-tokens with equal IDs is considered to have passed through the component
 * (no freeing, no unification of tokens). This handles situation when read order and write order
 * of related tokens differs, like in sorting components.
 * 
 * Suitable for SimpleCopy-like components, e.g. Ext/FastSort.
 * 
 * @author tkramolis (info@cloveretl.com)
 *         (c) Javlin, a.s. (www.cloveretl.com)
 *
 * @created 18.5.2012
 */
public class CopyComponentTokenTracker extends BasicComponentTokenTracker {

	private Token lastNewToken; 
	
	public CopyComponentTokenTracker(Node component) {
		super(component);
	}
	
	@Override
	public void writeToken(int outputPort, DataRecord tokenDR) {
		validateToken(tokenDR);
		
		Token token = (Token) tokenDR;
		if (lastNewToken == null || lastNewToken.getTokenId() != token.getTokenId()) {
			lastNewToken = token.duplicate();
		} else {
			initToken(token);
			linkTokens(lastNewToken, token);
		}
		
		super.writeToken(outputPort, token);
	}
	
}
